import { BaseErr, util, InsideErr } from "utils";
import { ChinaUnicomCookie } from "../const";
import { getDefaultCookie } from "./defaultCookie";
import { requestCardData } from "./requestCardData";
const db = uniCloud.database();
const collection = db.collection("token-valid");

// 获取db 缓存
async function getDbCache(): Promise<[err?: BaseErr, data?: any]> {
    let [err, res] = await util.awaitWrap(
        collection
            .where({
                "token-type": ChinaUnicomCookie,
            })
            .limit(1)
            .get()
    );
    if (err) {
        return [new InsideErr(err), undefined];
    }
    let { data = [] } = res || {};
    return [undefined, data[0]];
}

// 获取对应的cookie
async function getCardCookie(): Promise<
    [err?: BaseErr, data?: { id?: string; token?: string; valid: boolean }]
> {
    let [err, data] = await getDbCache();
    if (!util.nilValue(err)) {
        return [err, undefined];
    }

    let cookieData: { id?: string; token?: string; valid: boolean } = {
        valid: false,
    };
    // 来个默认值
    if (util.nilValue(data)) {
        let defaultCookie = getDefaultCookie();
        // 写入  数据库
        let res = await collection.add({
            token: defaultCookie,
            "token-type": ChinaUnicomCookie,
            valid: true,
            update: util.baseDateDes(new Date()),
        });
        cookieData = {
            token: defaultCookie,
            valid: true,
            id: res.id,
        };
    } else {
        // 已经有了
        cookieData = {
            token: data.token,
            valid: data.valid,
            id: data._id,
        };
    }
    return [undefined, cookieData];
}

// 修改cookie 有效
async function changeCardToken(valid: boolean, docId?: string) {
    if (docId) {
        await collection.doc(docId).update({
            valid,
            update: util.baseDateDes(new Date()),
        });
    }
}

// 获取解析后的数据
async function getCardData(): Promise<[err?: BaseErr, data?: any]> {
    // 获取数据库中的 cookie
    let [err, token] = await getCardCookie();
    if (!util.nilValue(err)) {
        return [err, undefined];
    }
    // 判断token 是否是无效的了
    if (token?.valid !== true || util.nilValue(token?.token)) {
        // 失效了
        return [new BaseErr(-4009, "token  已失效"), undefined];
    }

    // 请求 数据
    let [card_err, card_data] = await requestCardData(token.token!);
    if (!util.nilValue(card_err)) {
        // 把 token 设置为无效
        await changeCardToken(false, token.id);
    }
    return [card_err, card_data];
}

export { getCardData };
